package com.siha_back.utils;

import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

public class DifyApiClient {
    private static final String API_BASE_URL = "https://api.dify.ai/v1";
    private final String apiKey;

    public DifyApiClient(String apiKey) {
        this.apiKey = apiKey;
    }

    public String post(String endpoint, String requestBody) throws Exception {
        // 配置超时设置
        RequestConfig config = RequestConfig.custom()
                .setConnectTimeout(5000) // 5秒连接超时
                .setSocketTimeout(30000) // 30秒socket超时
                .build();

        try (CloseableHttpClient httpClient = HttpClients.custom()
                .setDefaultRequestConfig(config)
                .build()) {

            HttpPost httpPost = new HttpPost(API_BASE_URL + endpoint);

            // 设置请求头
            httpPost.setHeader("Authorization", "Bearer " + apiKey);
            httpPost.setHeader("Content-Type", "application/json");
            httpPost.setHeader("Accept", "application/json");

            // 设置请求体
            httpPost.setEntity(new StringEntity(requestBody, "UTF-8"));

            // 执行请求
            try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
                // 检查HTTP状态码
                int statusCode = response.getStatusLine().getStatusCode();
                if (statusCode != 200) {
                    throw new RuntimeException("API请求失败，状态码: " + statusCode);
                }

                HttpEntity entity = response.getEntity();
                return EntityUtils.toString(entity, "UTF-8");
            }
        }
    }
}
